﻿using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CompactMapper.Orm.Annotations;
using CompactMapper.Orm.Contracts;
using CompactMapper.Orm.UnitOfWork.Mappings;
using System;

namespace CompactMapper.Orm.Tests
{
    [TestClass]
    public class SingleRelationDeleteCascadeTests : OrmInMemoryTest
    {
        [Table]
        public class SingleParent : IKeyedPersistent
        {
            [GuidPrimaryKey]
            public IKey Key { get; set; }

            [Single]
            public SingleDescendant SingleDescendant { get; set; }

            public SingleParent()
            {
                Key = AbstractKeyFactory.For<Guid>().New();
            }
        }

        [Table]
        public class SingleDescendant : IKeyedPersistent
        {
            [GuidPrimaryKey]
            public IKey Key { get; set; }

            public SingleDescendant()
            {
                Key = AbstractKeyFactory.For<Guid>().New();
            }
        }

        [TestMethod]
        public void SingleRelation_DeleteCascades()
        {
            var parent = new SingleParent() { SingleDescendant = new SingleDescendant() };
            using (var unitOfWork = GetKeyedUnitOfWork<SingleParent>())
            {
                unitOfWork.MakePersistent(parent);
            }
            using (var unitOfWork = GetKeyedUnitOfWork<SingleParent>())
            {
                unitOfWork.Delete(parent.Key);
            }
            using (var unitOfWork = GetKeyedUnitOfWork<SingleParent>())
            {
                Assert.IsFalse(unitOfWork.GetAll().Any(), "Parent wasn't deleted");
            }
            using (var unitOfWork = GetKeyedUnitOfWork<SingleDescendant>())
            {
                Assert.IsFalse(unitOfWork.GetAll().Any(), "Descendant wasn't deleted");
            }
        }
    }
}
